import { IAppOption, ISwiper, IProduct, IResultArray, IBanner } from "../../../typings";
import { eventBus } from "../../utils/util";

const app = getApp<IAppOption>()
Page({
  data: {
    currentSwiper: '',
    swiperList: [] as ISwiper[],
    notice: '新品上市：芒果椰奶冻，限时特惠中！',
    hotProducts: [] as IProduct[],
    hotProductsLoading: false,
    currentProduct: {} as IProduct,
    specDrawerVisible: false,
  },
  onLoad() {
    this.fetchBanners()
    this.fetchHotProducts()
  },
  fetchBanners() {
    wx.showLoading({
      title: '加载中',
    })

    wx.cloud.callFunction({
      name: 'getBanners',
      data: {},
      success: res => {
        const result = res.result as IResultArray<IBanner>
        if (result.success && result.data.length > 0) {
          const banners = result.data.map(item => ({
            value: item.image,
            ariaLabel: item.title || '轮播图'
          })) as ISwiper[]

          this.setData({
            swiperList: banners,
            currentSwiper: banners[0].value
          })
        } else {
          this.setData({
            swiperList: [],
            currentSwiper: ""
          })

          if (!result.success) {
            console.error('获取轮播图失败:', result.errMsg)
          }
        }
      },
      fail: err => {
        console.error('调用云函数失败:', err)
        this.setData({
          swiperList: [],
          currentSwiper: ""
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  fetchHotProducts() {
    this.setData({
      hotProductsLoading: true
    })

    wx.cloud.callFunction({
      name: 'getProducts',
      data: {
        type: 'hot'
      },
    }).then(res => {
      const result = res.result as IResultArray<IProduct>
      if (result.success && result.data.length > 0) {
        this.setData({
          hotProducts: result.data
        })
      } else {
        this.setData({
          hotProducts: []
        })

        if (!result.success) {
          console.error('获取热门商品失败:', result.errMsg)
        }
      }
    }).catch(err => {
      console.error('调用云函数失败:', err)
      this.setData({
        hotProducts: []
      })
    }).finally(() => {
      this.setData({
        hotProductsLoading: false
      })
      wx.hideLoading()
    })
  },

  // 打开规格选择抽屉
  openSpecDrawer(e: any) {
    const product = e.currentTarget.dataset.product
    this.setData({
      currentProduct: product,
      specDrawerVisible: true
    })
  },

  // 关闭规格选择抽屉
  onSpecDrawerClose() {
    this.setData({
      specDrawerVisible: false
    })
  },
  goToMenu() {
    eventBus.emit("tabSwitch", "menu")
  },
});
